<template>
  <el-container class="main-layout">
    <el-aside class="main-layout__aside" :data-collapse="asideCollapse">
      <header>
        <!-- logo -->
        <router-link to="/home"></router-link>
      </header>
      <section class="aside__body">
        <!-- 菜单 -->
        <TheMenu
          :collapse="asideCollapse"
          :data="menus"
          :default-active="activePath"
          @select="handleSelect"
        />
      </section>
      </footer>-->
    </el-aside>
    <el-container>
      <el-header
        class="main-layout__header"
        :style="{
          height: asideCollapse ? '48px' : '48px',
        }"
      >
        <section class="main-layout__breadcrumb">
          <TheBreadcrumb :data="breadcrumbData" @click-item="clickBreadcrumb" />
          <div
            v-show="$route.meta.touchBar"
            class="main-layout__back-button"
            @click="$router.go(-1)"
          >
            <i title="返回" class="iconfont icon-ffanhui-" />
          </div>
        </section>
        <section class="main-layout__tool">
          <Screenfull />
          <!-- 用户头像 -->
          <UserAvatar
            :name="name"
            @click-update-password="updateUPassword"
            @click-logout="handleLogout"
          />
          <!-- 系统管理 -->
          <SysManagement v-if="systemConf.length" :data="systemConf" @click-item="clickItem" />
          <ThemePicker
            :selected="theme"
            :data="themes"
            :collapse="asideCollapse"
            @theme-change="themeChange"
          />
        </section>
      </el-header>
      <el-main class="main-layout__main" id="layout_body">
        <section class="main-layout__main-inner re-md-sm-padding" ref="mainBody">
          <navigation>
            <router-view></router-view>
          </navigation>
        </section>
      </el-main>
    </el-container>
  </el-container>
</template>

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import TheBreadcrumb, {
  DataType as BreadcrumbDataType
} from "@/components/TheBreadcrumb.vue";
import UserAvatar from "@/components/UserAvatar.vue";
import ThemePicker from "@/components/ThemePicker.vue";
import { namespace, State } from "vuex-class";
import { Menu, SystemConf } from "@/store/user";
import { Route, RouteRecord } from "vue-router";
import { Action } from "vuex";
import { EventBus, Screenfull, TheMenu } from "feok-lib";
import { filter } from "lodash";
import SysManagement from "@/components/SysManagement.vue";

const userModule = namespace("user");
const appModule = namespace("app");

Component.registerHooks(["beforeRouteEnter"]);

@Component({
  components: {
    TheMenu,
    TheBreadcrumb,
    UserAvatar,
    ThemePicker,
    Screenfull,
    SysManagement
  }
})
export default class MainLayout extends Vue {
  @userModule.State("menus") public menus!: Menu;
  @userModule.State("systemConf") public systemConf!: SystemConf;
  @userModule.State("name") public name!: string;
  @userModule.Action("logout") public logout: any;
  @userModule.Action("getMenus") public getMenus: any;
  @userModule.Action("getLoginUserInfo") public getLoginUserInfo: any;
  @appModule.State("asideCollapse") public asideCollapse!: boolean;
  @appModule.State("themes") public themes!: boolean;
  @appModule.State("theme") public theme!: boolean;
  @appModule.Action("toggleAsideStatus") public toggleAsideStatus: any;
  @appModule.Action("changeTheme") public changeTheme: any;
  @appModule.Action("initApp") public initApp: any;

  private activePath = "";
  private breadcrumbData: BreadcrumbDataType[] = [];

  /**
   * 路由钩子
   */
  public async beforeRouteEnter(to: any, from: any, next: any) {
    next(async (vm: MainLayout) => {
      try {
        await vm.initApp();
      } catch (error) {
        // console.log(error);
      }
      return true;
    });
  }

  public handleSelect(path: string) {
    this.$router.push({ name: path });
    console.log("arguments", arguments);
  }

  @Watch("$route")
  public onRouteChange(val: Route) {
    const { path, matched } = val;
    this.activePath = matched[matched.length - 2].name || (val.name as string);
    const breadcrumbData = matched.map(
      (route: RouteRecord): BreadcrumbDataType => ({
        path: route.name as string,
        name: route.meta ? route.meta.title || "" : ""
      })
    );
    this.breadcrumbData = filter(
      breadcrumbData,
      (item: any) => item.name !== ""
    );
  }

  public clickItem(
    key: string,
    item: {
      key: string;
      name: string;
    }
  ) {
    EventBus.$emit("gotoSysView", key);
  }

  public updateUPassword() {
    this.$router.push({ name: "update_password" });
  }
  public async handleLogout() {
    await this.logout();
    window.location.href = `${process.env.VUE_APP_BASE_API_URL}`;
  }
  public clickBreadcrumb(path: string) {
    this.$router.push({ name: path });
  }

  public clickBadge() {
    EventBus.$emit("showTodos");
  }

  public themeChange(val: string) {
    this.changeTheme({
      code: val
    });
  }
  public async created() {
    await Promise.all([this.getMenus(), this.getLoginUserInfo()]);
    this.onRouteChange(this.$route);
    EventBus.$emit("appCreated");
  }
  /**
   * 安装 event bus
   */
  public installEventBus() {
    EventBus.$on("bodyOverflowHiden", () => {
      const $mainBody: any = this.$refs.mainBody;
      $mainBody.style.overflow = "hidden";
    });
    EventBus.$on("bodyOverflowAuto", () => {
      const $mainBody: any = this.$refs.mainBody;
      $mainBody.style.overflow = null;
    });
    EventBus.$on("tablePageChange", () => {
      const $mainBody: any = this.$refs.mainBody;
      $mainBody.scrollTop = 0;
    });
  }

  /**
   * 卸载 event bus
   */
  public uninstallEventBus() {
    EventBus.$off("bodyOverflowHiden");
    EventBus.$off("bodyOverflowAuto");
    EventBus.$off("tablePageChange");
  }

  public mounted() {
    this.installEventBus();
  }

  public beforeDestroy() {
    this.uninstallEventBus();
  }
}
</script>

<style lang="less" scoped>
@touchBarHeight: 35px; // touch bar 高度
.main-layout {
  height: 100%;
  width: 100%;
  &__aside {
    position: relative;
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #445268;
    width: 210px !important;
    transition: width 0.5s;
    &[data-collapse="true"] {
      width: 64px !important;
      footer {
        justify-content: center;
        padding-right: 0;
      }
    }
    header {
      display: flex;
      align-items: center;
      justify-content: center;
      // padding-left: 18px;
      img {
        width: 50%;
        margin-left: 20px;
      }
    }
    .aside__body {
      flex: 1;
      border-top: 1px solid #566280;
      box-shadow: 0px -1px 1px #3c455a;
      overflow: auto;
      overflow-x: hidden;
      &::-webkit-scrollbar {
        display: none;
      }
    }
    footer {
      cursor: pointer;
      display: flex;
      align-items: center;
      height: 48px;
      justify-content: flex-end;
      padding-right: 16px;
      border-top: 1px solid #566280;
      box-shadow: 0px -1px 1px #3c455a;
      &:hover {
        background: rgba(0, 0, 0, 0.2);
      }
      &:active {
        background: rgba(0, 0, 0, 0.3);
      }
      .iconfont {
        color: #fff;
      }
    }
  }
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #dcdfe6;
    box-shadow: 1px 1px 3px #dcdfe6;
    transition: all 0.3s;
    height: 45px;
  }
  &__back-button {
    color: #303133;
    cursor: pointer;
    display: block;
    padding: 0 15px;
    display: flex;
    height: 100%;
    align-items: center;
    margin-left: 8px;
    &:hover {
      background-color: #f5f7fa;
    }
  }
  &__breadcrumb {
    display: flex;
    height: 100%;
    align-items: center;
  }
  &__tool {
    & > .tool__item {
      margin-right: 12px;
    }
    & > .tool__badge {
      cursor: pointer;
      transform: translateY(6px);
    }
  }
  &__main {
    position: relative;
    background: #f2f3f7;
  }
  &__main-inner {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    overflow: auto;
    &[data-toolbar] {
      top: @touchBarHeight + 2px;
    }
  }
  &__touch-bar {
    position: absolute;
    display: flex;
    padding-left: 25px;
    align-items: center;
    top: 0;
    left: 0;
    right: 0;
    height: @touchBarHeight;
    background: #fff;
    border-bottom: #dcdfe6;
    box-shadow: 0 1px 3px #dcdfe6;
  }
  &__alert {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 399;
  }
  .logo {
    width: 80px;
    margin: 20px auto;
    display: block;
  }
  .smalllogo {
    width: 60px;
    margin: 20px auto;
    display: block;
  }
  .main-layout__tool {
    display: flex;
    align-items: center;
  }
}
// @media screen and (max-width: 1366px) {
.main-layout {
  &__aside {
    width: 160px !important;
  }
  .logo {
    width: 60%;
    margin: 16px auto;
  }
}
// }
</style>
